package com.gxuwz.endrskyweather;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.widget.ViewPager2;

import com.gxuwz.endrskyweather.adapter.ForecastPagerAdapter;
import com.google.android.material.button.MaterialButton;
import com.gxuwz.endrskyweather.viewmodel.CityWeatherViewModel;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class WeatherPagerFragment extends Fragment {

    private static final String ARG_CITY_NAME = "city_name";
    private static final String ARG_CITY_CODE = "city_code";
    private static final String TAG = "WeatherPagerFragment";
    private CityWeatherViewModel viewModel;

    // 当前天气信息的组件
    private TextView tvTimeYear;
    private TextView tvTimeMonthDay;
    private TextView tvTimeTime;
    private TextView tvSunrise;
    private TextView tvSunset;
    private ImageView ivWeatherIcon;
    private TextView tvTemp;
    private TextView tvWeather;
    private TextView tvWind;
    private TextView tvWindLevel;
    private TextView tvHumidity;

    // 预警信息的组件
    private CardView cvWarning;
    private TextView tvWarningContent;

    // 空气指数区域的组件
    private TextView tvAqi;
    private TextView tvPm25;
    //TODO: 空气指数尚未完全，还要添加能见度等指数

    // 生活指数区域的组件
    private TextView tvDress;
    private TextView tvWashCar;
    private TextView tvSport;
    private TextView tvUv;
    private TextView tvCold;
    private TextView tvAllergy;

    // 天气预报 ViewPager 模块的组件
    private ViewPager2 forecastViewPager;
    private MaterialButton btn_24h;
    private MaterialButton btn_7d;
    private MaterialButton btn_15d;
    private ForecastPagerAdapter forecastPagerAdapter;

    // 判断观测者是否已经订阅了天气信息
    private boolean isObserver;

    // Handler 和 Runnable 用于实时更新时间
    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable updateTimeRunnable = new Runnable() {
        @Override
        public void run() {
            updateCurrentTime();
            handler.postDelayed(this, 1000); // 每秒更新一次
        }
    };

    public static WeatherPagerFragment newInstance(String cityName, String cityCode) {
        WeatherPagerFragment fragment = new WeatherPagerFragment();
        Bundle args = new Bundle();
        args.putString(ARG_CITY_NAME, cityName);
        args.putString(ARG_CITY_CODE, cityCode);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.weather_context, container, false);
        viewModel = new ViewModelProvider(this).get(CityWeatherViewModel.class);
        isObserver = false;
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 初始化天气信息的组件
        tvTimeYear = view.findViewById(R.id.tv_time_year);
        tvTimeMonthDay = view.findViewById(R.id.tv_time_date);
        tvTimeTime = view.findViewById(R.id.tv_time_time);
        tvSunrise = view.findViewById(R.id.tv_sunrise_time);
        tvSunset = view.findViewById(R.id.tv_sunset_time);
        ivWeatherIcon = view.findViewById(R.id.iv_now_weather_icon);
        tvTemp = view.findViewById(R.id.tv_now_weather_temp);
        tvWeather = view.findViewById(R.id.tv_now_weather_status);
        tvWind = view.findViewById(R.id.tv_now_weather_wind);
        tvWindLevel = view.findViewById(R.id.tv_now_weather_wind_level);
        tvHumidity = view.findViewById(R.id.tv_now_weather_humidity);

        // 初始化空气指数区域的组件
        tvAqi = view.findViewById(R.id.tv_aqi);
        tvPm25 = view.findViewById(R.id.tv_pm25);

        // 初始化预警信息区域的组件
        cvWarning = view.findViewById(R.id.alarm_card);
        tvWarningContent = view.findViewById(R.id.tv_alarm_content);

        // 初始化生活指数区域的组件
        tvDress = view.findViewById(R.id.tv_dress_index);
        tvWashCar = view.findViewById(R.id.tv_car_wash_index);
        tvSport = view.findViewById(R.id.tv_sport_index);
        tvUv = view.findViewById(R.id.tv_uv_index);
        tvCold = view.findViewById(R.id.tv_cold_index);
        tvAllergy = view.findViewById(R.id.tv_allergy_index);

        forecastViewPager = view.findViewById(R.id.weather_view_pager);
        btn_24h = view.findViewById(R.id.btn_24h);
        btn_7d = view.findViewById(R.id.btn_7d);
        btn_15d = view.findViewById(R.id.btn_15d);

        // 初始化 ForecastPagerAdapter
        String cityName = getArguments() != null ? getArguments().getString(ARG_CITY_NAME) : "";
        String cityCode = getArguments() != null ? getArguments().getString(ARG_CITY_CODE) : "";
        forecastPagerAdapter = new ForecastPagerAdapter(this, cityName, cityCode);
        forecastViewPager.setAdapter(forecastPagerAdapter);

        // 观测者订阅
        if (!isObserver) {
            // 订阅当前天气信息
            viewModel.getWeatherNow().observe(getViewLifecycleOwner(), weatherNow -> {
                if (weatherNow != null) {
                    Log.d("WeatherPagerFragment", "weatherNow: 当前天气信息的城市：" + weatherNow.getCityname());
                    Log.d("WeatherPagerFragment", "weatherNow: " + weatherNow.toString() + viewModel.getAqiLevel());
                    // 更新天气信息
                    try {
                        tvSunrise.setText(viewModel.getDay().getSunUp());
                        tvSunset.setText(viewModel.getNight().getSunDown());
                        tvTemp.setText(weatherNow.getTemp());
                        tvWeather.setText(weatherNow.getWeather());
                        ivWeatherIcon.setImageResource(getResources().getIdentifier(
                                weatherNow.getWeathercode(), "drawable", requireContext().getPackageName()));
                        tvWind.setText(weatherNow.getWD());
                        tvWindLevel.setText(weatherNow.getWS());
                        tvHumidity.setText(weatherNow.getSD());
                        tvAqi.setText(viewModel.getAqiLevel());
                        tvPm25.setText(weatherNow.getAqi_pm25());
                    } catch (Exception e) {
                        Toast.makeText(requireContext(),"天气信息获取失败", Toast.LENGTH_SHORT).show();
                        Log.e("WeatherPagerFragment", "weatherNow: " + e.getMessage());
                    }
                }
            });
            // 订阅生活指数信息
            viewModel.getLifeIndex().observe(getViewLifecycleOwner(), lifeIndex -> {
                Log.d("WeatherPagerFragment", "lifeIndex: " + lifeIndex.toString());
                if (lifeIndex != null) {
                    try {
                        tvDress.setText("穿衣指数：" + lifeIndex.getDress().getState());
                        tvWashCar.setText("洗车指数：" + lifeIndex.getCarWash().getState());
                        tvSport.setText("运动指数：" + lifeIndex.getSport().getState());
                        tvUv.setText("紫外线：" + lifeIndex.getUltraviolet().getState());
                        tvCold.setText("感冒指数：" + lifeIndex.getCold().getState());
                        tvAllergy.setText("过敏指数：" + lifeIndex.getAllergy().getState());
                    }catch (Exception e){
                        Toast.makeText(requireContext(), "生活指数获取失败", Toast.LENGTH_SHORT).show();
                        Log.e("WeaterPagerFragment", "lifeIndex: " + e.getMessage());
                    }
                }
            });
            // 订阅预警信息
            viewModel.getAlarmList().observe(getViewLifecycleOwner(), alarmList -> {
                Log.d("WeatherPagerFragment", "alarmList: " + alarmList.toString());
                if (alarmList != null) {
                    try {
                        cvWarning.setVisibility(View.VISIBLE);
                        String text = "预警信息：" + alarmList.getSignalLevel() + "级" + "\n" + alarmList.getIssueContent();
                        tvWarningContent.setText(text);
                    } catch (Exception e) {
                        Toast.makeText(requireContext(), "预警信息获取失败", Toast.LENGTH_SHORT).show();
                        Log.e("WeatherPagerFragment", "alarmList: " + e.getMessage());
                    }
                } else {
                    cvWarning.setVisibility(View.GONE);
                }
            });
            isObserver = true;
        }

        // 加载天气信息
        viewModel.loadWeatherNow(this.getArguments().getString(ARG_CITY_CODE));
        // 加载生活指数信息：已经被加载天气接管了
//        viewModel.loadLifeIndex(this.getArguments().getString(ARG_CITY_CODE));

        // 设置按钮点击事件
        btn_24h.setOnClickListener(v -> {
            forecastViewPager.setCurrentItem(0);
            updateButtonColors(0);
        });
        btn_7d.setOnClickListener(v -> {
            forecastViewPager.setCurrentItem(1);
            updateButtonColors(1);
        });
        btn_15d.setOnClickListener(v -> {
            forecastViewPager.setCurrentItem(2);
            updateButtonColors(2);
        });

        // 处理 ViewPager2 嵌套滚动冲突
        forecastViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                updateButtonColors(position);
            }
        });

        // 初始化按钮颜色
        updateButtonColors(0);

        // 处理 ViewPager2 嵌套滚动冲突

        forecastViewPager.setOnTouchListener((v, event) -> {
            v.getParent().requestDisallowInterceptTouchEvent(true);
            return false;
        });

        // 启动时间更新
        handler.post(updateTimeRunnable);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 停止时间更新
        handler.removeCallbacks(updateTimeRunnable);
    }

    private void updateCurrentTime() {
        SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy年", Locale.getDefault());
        SimpleDateFormat sdfMonthDay = new SimpleDateFormat("MM月dd日", Locale.getDefault());
        SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());

        String currentTime = sdfTime.format(new Date());
        String currentYear = sdfYear.format(new Date());
        String currentMonthDay = sdfMonthDay.format(new Date());

        tvTimeYear.setText(currentYear);
        tvTimeMonthDay.setText(currentMonthDay);
        tvTimeTime.setText(currentTime);
    }

    private void updateButtonColors(int selectedPosition) {
        btn_24h.setBackgroundTintList(requireContext().getResources().getColorStateList(
                selectedPosition == 0 ? R.color.forecast_tab_selected : R.color.forecast_tab_blue));
        btn_7d.setBackgroundTintList(requireContext().getResources().getColorStateList(
                selectedPosition == 1 ? R.color.forecast_tab_selected : R.color.forecast_tab_blue));
        btn_15d.setBackgroundTintList(requireContext().getResources().getColorStateList(
                selectedPosition == 2 ? R.color.forecast_tab_selected : R.color.forecast_tab_blue));
    }
}
